package cn.xzqwjw.taskmanager.security.handler;

import cn.xzqwjw.taskmanager.common.customEnum.ResponseCodeEnum;
import cn.xzqwjw.taskmanager.domain.vo.ResponseVo;
import cn.xzqwjw.taskmanager.utils.ResponseUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义权限不足拒绝访问的错误输出格式，这里是输出成json
 *
 * @author rush
 */
@Component
public class AuthAccessDeniedHandler implements AccessDeniedHandler {

  @Override
  public void handle(HttpServletRequest request,
                     HttpServletResponse response,
                     AccessDeniedException e) {
    // 回复一个 403 的 Response
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    String statusCode = ResponseCodeEnum.FORBIDDEN.getStatusCode();
    String message = e.getMessage();
    ResponseUtil.writeJson(response, ResponseVo.error(statusCode, message));
  }

}
